/* Random Book Finder, version [0.0.4a-r3]
Originally from: http://en.wikibooks.org/wiki/User:Splarka/randbook.js
Based roughly on http://en.wikibooks.org/w/index.php?title=MediaWiki:RandomBook.js&oldid=1209572 by Darklama.

Notes:
* Grab only 10 random pages in one go because that is the limit.
* 2 iterations may be needed because 10.5% of pages are books.
* Refer to books by their ID to find them even when moved.
* Append links instead with: mw.config.set( 'random_book_list', true ); (add this in your [[Special:MyPage/common.js]]);
*/

$(document).ready( function($) {
	var	reqid = 0, random_list = mw.config.get( 'random_book_list', false ),
		randbookLink = mw.util.addPortletLink( 'p-Navigation', '#', 'Random book', 'n-randbook', 'Show me a random book', 'x' ),
		bookLink = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?curid=';

	function fetch_categories( id, callback ) {
		$.getJSON( mw.util.wikiScript( 'api' ), {
			format:		'json',
			action:		'query',
			prop:		'categories',
			cllimit:	100,
			generator:	'random',
			grnnamespace:	'0|110',
			grnlimit:	10,
			requestid:	id
		}, callback );
	}

	function showRandBookCB(obj) {
		var pages;

		if ( !obj.query || !obj.query.pages ) {
			$(randbookLink).append('<span class="error">error</span>');
			if ( random_list ) {
				removeSpinner( 'randbook' );
			}
			return;
		}

		pages = $.map( obj.query.pages, function(page, id) {
			return $.map( page.categories || [], function( cat ) {
				if ( cat.title.indexOf( 'Category:Alphabetical/' ) === 0 ) {
					return { id: id, title: page.title };
				}
			});
		});

		if ( !pages.length ) {
			// didn't find any, try again
			++reqid;
			fetch_categories( reqid, showRandBookCB );
			return;
		}

		if ( !random_list ) {
			window.location.assign( bookLink + pages[ Math.floor( Math.random()*pages.length ) ].id );
			return;
		}

		removeSpinner( 'randbook' );
		$.each( pages, function() {
			$(randbookLink).append('<div><a href="' + bookLink + this.id + '"> \u2022\u00A0' + this.title + '</a></div>');
		});
	}

	$(randbookLink).click( function(e) {
		if ( random_list ) {
			injectSpinner( this, 'randbook' );
		}
		++reqid;
		fetch_categories( reqid, showRandBookCB );
		e.preventDefault();
	});
});